//
//  QCBaseViewController.m
//  QCAppProject
//
//  Created by yjl on 2021/8/16.
//

#import "QCBaseViewController.h"
#import "UIBarButtonItem+Extension.h"

@interface QCBaseViewController () <UIGestureRecognizerDelegate>

@property (nonatomic, strong) UILabel * navTitleLabel; //导航栏标题
@property (nonatomic,strong) UIBarButtonItem *rightBarItem;
@property (nonatomic, strong) UIImageView *navBarHairlineImageView;//导航栏线
@property(nonatomic,strong)UIToolbar *addToolbar;


@end

@implementation QCBaseViewController
@synthesize backBut,rightBarItem,activtyTextField;;

- (id)init {
    if (self = [super init]) {
//        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
//        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil object:(id)object {
    
    self = [super initWithNibName:nibNameOrNil bundle:nil];
    if (self) {
//        self.hidesBottomBarWhenPushed = YES;
    }
    
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([[UIDevice currentDevice] systemVersion].floatValue>=7.0) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
        [self setAutomaticallyAdjustsScrollViewInsets:NO];
    }
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self hideNavBarHairline];
    // 加载返回按钮
    [self drawBackBut];
    if ([self.navigationController.viewControllers count] > 1) {
        self.isShowBackButton = YES;
    }
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17 weight:6],NSForegroundColorAttributeName:QCWhite}];
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
//    [self.view addGestureRecognizer:tap];
    
}

//查看当前vc是否释放
- (void)dealloc {
    QCLog(@"dealloc-->%@",NSStringFromClass([self class]));
    // 停止所有操作
//    [[AFHTTPSessionManager manager].operationQueue cancelAllOperations];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //解决动画消失问题
    [UIView setAnimationsEnabled:YES];
//    self.navigationController.navigationBarHidden = NO;
//    self.navigationController.navigationBar.translucent = NO;
//    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
//    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    backBut.hidden = !self.isShowBackButton;
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]){
        self.navigationController.interactivePopGestureRecognizer.enabled=YES;
        self.navigationController.interactivePopGestureRecognizer.delegate=self;
    }
    
    if (self.navigationController.viewControllers.count == 1) {
        self.tabBarController.tabBar.hidden = NO;
//        [self.tabBarController.tabBar setHidden:NO];
    }
    
    self.navBarRightBtn.hidden = NO;
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

//子类如果想要显示导航栏下的黑线重写该方法即可
- (void)setHideNavBottomBlackLine:(BOOL)isHidden {
    self.navigationController.navigationBar.subviews[0].subviews[0].hidden = isHidden;
    self.navigationController.navigationBar.subviews[0].subviews[0].backgroundColor = QCLineColor;
}

- (void)hideNavBarHairline {
    //隐藏导航栏黑线
    _navBarHairlineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    _navBarHairlineImageView.hidden = YES;
}

//隐藏导航栏黑线
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

#pragma mark -滑动返回代理
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    //如果controller不是第一层则返回
    if([gestureRecognizer isEqual:self.navigationController.interactivePopGestureRecognizer]){
        if([self viewWillPopByGestureRecognizer:gestureRecognizer]&&![self isEqual:[self.navigationController.viewControllers firstObject]]){
            return YES;
        }
        return NO;
    }
    return YES;
}

//子类如果需要自己控制是否滑动返回，重写该方法,默认开启
- (BOOL)viewWillPopByGestureRecognizer:(UIGestureRecognizer*)gestureRecognizer {
    return YES;
}

- (void)drawBackBut {
    if (!backBut) {
        backBut = [UIButton buttonWithType:UIButtonTypeCustom];
        backBut.titleLabel.font = FONT_PS(14);
        [backBut setImage:[UIImage imageNamed:@"ic_back_24pt_white"] forState:UIControlStateNormal];
        [backBut setImage:[UIImage imageNamed:@"ic_back_24pt_white"] forState:UIControlStateHighlighted];
    }
    
    [self setupNavBackItemStyle];
    
    UIBarButtonItem *barBtnItem = [[UIBarButtonItem alloc] initWithCustomView:backBut];
    self.navigationItem.leftBarButtonItem = barBtnItem;
    
    
    [backBut addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    backBut.hidden = !self.isShowBackButton;
    //
    _navTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0,140, 24 )];
    _navTitleLabel.backgroundColor = [UIColor clearColor];
    _navTitleLabel.font = [UIFont boldSystemFontOfSize:20.0f];
    _navTitleLabel.textAlignment = NSTextAlignmentCenter;
    //_navTitleLabel.textColor = [UIColor whiteColor];
    _navTitleLabel.textColor = [UIColor blackColor];
    
    _navBarRightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _navBarRightBtn.frame = CGRectMake(0, 0, 40, 40);
    _navBarRightBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentRight;
    _navBarRightBtn.titleLabel.font = FONT_PM(14);
    //    [_navBarRightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_navBarRightBtn addTarget:self action:@selector(navBarRightBtnAction:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 返回按钮事件

//- (void)tapAction {
//    [self.view endEditing:YES];//关闭键盘
//}

// 返回事件
- (void)backAction:(id)sender {
//    [QCProgressHUD hideHUD];
    [self back];
}

- (void)back{
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}

//11
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {      // return NO to disallow editing.
    activtyTextField = nil;
    activtyTextField = textField;
    return YES;
}


- (void)hideKeyboard {
    [activtyTextField resignFirstResponder];
}


#pragma mark - ReWrite
- (void)setNavBarTitle:(NSString *)title {
    _navTitleLabel.text = title;
    self.navigationItem.titleView = _navTitleLabel;
}

#pragma mark-rightBarButtonItem
- (void)setNavBarRightBtnWithTitle:(NSString *)title andImageName:(NSString *)imgName {
    if([title length]>0){
        _navBarRightBtn.hidden = NO;
        CGFloat width = [title sizeWithAttributes:@{NSFontAttributeName:_navBarRightBtn.titleLabel.font}].width;
        _navBarRightBtn.frame = CGRectMake(0, 0, width > 60 ? 60 : width, 40);
        [_navBarRightBtn setTitle:title forState:UIControlStateNormal];
        [_navBarRightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        rightBarItem=[[UIBarButtonItem alloc] initWithCustomView:_navBarRightBtn];
        self.navigationItem.rightBarButtonItem = rightBarItem;
    }
    if (imgName.length>0) {
        _navBarRightBtn.hidden = NO;
        _navBarRightBtn.frame = CGRectMake(0, 0, 40, 40);
        [_navBarRightBtn setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
        rightBarItem=[[UIBarButtonItem alloc] initWithCustomView:_navBarRightBtn];
        self.navigationItem.rightBarButtonItem = rightBarItem;
    }
}

#pragma mark-----设置右边按钮
-(void)setRightButton:(id)rightButton{
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = [UIColor blackColor];
    textAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:14];
    if ([rightButton isKindOfClass:[UIImage class]]) {
        self.navigationItem.rightBarButtonItem=[UIBarButtonItem itemWithTarget:self action:@selector(rightButtonClick) image:rightButton highImage:rightButton];
        [self.navigationItem.rightBarButtonItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
    }
    if ([rightButton isKindOfClass:[NSString class]]) {
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:rightButton style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonClick)];
        [self.navigationItem.rightBarButtonItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
    }
    
    
}

#pragma mark-----点击右按钮出发事情
-(void)rightButtonClick{
    
    
}

#pragma mark - 重设导航栏上按钮控件显示
//- (void)resetNavBarBtnsWithLeftBtnImg:(NSString *)leftBtnImg rigBtnImg:(NSString *)rigBtnImg {
//    //
//    UIImage *image = nil;
//    if (_navBarRightBtn && ![QCUtil isBlankString:rigBtnImg]) {
//        _navBarRightBtn.hidden = NO;
//        image = [QCCache memoryValueForKey:rigBtnImg];
//        if (!image) {
//            image = [UIImage imageNamed:rigBtnImg];
//            [QCCache setMemoryValue:image forKey:rigBtnImg];
//        }
//
//        [_navBarRightBtn setImage:image forState:UIControlStateNormal];
//    } else {
//        _navBarRightBtn.hidden = YES;
//    }
//
//    image = [QCCache memoryValueForKey:leftBtnImg];
//    if (!image) {
//        image = [UIImage imageNamed:leftBtnImg];
//        [QCCache setMemoryValue:image forKey:leftBtnImg];
//    }
//
//    [backBut setImage:image forState:UIControlStateNormal];
//    [backBut setImage:image forState:UIControlStateHighlighted];
//}

//设置按钮透明度
- (void)resetBtnsAlpha:(CGFloat)alpha {
    //    MLog("%f\n", alpha);
    backBut.alpha = alpha;
    _navBarRightBtn.alpha = alpha;
}

- (void)setNavBarRightBtnEnabled:(BOOL)enabled {
    
    rightBarItem.enabled=enabled;
    _navBarRightBtn.enabled=enabled;
}


- (void)navBarRightBtnAction:(id)sender {
    //子类重写该方法
    
}

#pragma mark - ShareViewDelegate
- (void)shareBtnHandled:(NSInteger)tag{
    //子类重写该方法
}

- (void)setNavBarLeftBtnImg:(NSString *)imgName {
    if([imgName length] > 0) {
        [self.backBut setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
        [self.backBut setImage:[UIImage imageNamed:imgName] forState:UIControlStateHighlighted];
    }
}

#pragma mark - 设置导航返回按钮样式
- (void)setupNavBackItemStyle {
    if (self.backTitle) {
        [self configureBackTitleStyle];
    } else {
        [self configureNavBackDefaultStyle];
    }
}

- (void)configureBackTitleStyle {
    self.backBut.frame = CGRectMake(0, 0, 60, 40);
    [self.backBut setImageEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 0)];
    [self.backBut setTitleEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 0)];
    [self.backBut setTitle:self.backTitle forState:UIControlStateNormal];
    [self.backBut setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.backBut setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
}


- (void)configureNavBackDefaultStyle {
    self.backBut.frame = CGRectMake(0, 0, 40, 40);
    [self.backBut setImageEdgeInsets:UIEdgeInsetsMake(0, -25, 0, 0)];
}

- (UIToolbar *)addToolbar
{
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 44)];
    toolbar.tintColor = [UIColor blackColor];
    toolbar.backgroundColor = [UIColor lightGrayColor];
    UIBarButtonItem *prevItem = [[UIBarButtonItem alloc] initWithTitle:@"  <  " style:UIBarButtonItemStylePlain target:self action:@selector(numberFieldCancle)];
    UIBarButtonItem *nextItem = [[UIBarButtonItem alloc] initWithTitle:@"  >  " style:UIBarButtonItemStylePlain target:self action:@selector(numberFieldCancle)];
    UIBarButtonItem *flbSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"完成",nil) style:UIBarButtonItemStylePlain target:self action:@selector(numberFieldCancle)];
    toolbar.items = @[prevItem,nextItem,flbSpace, doneItem];
    return toolbar;
}

-(void)numberFieldCancle{
    
    
}

- (void)setNoDataView:(NSString *)tipString imageName:(NSString *)imageName originY:(CGFloat)originY {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, originY, SCREEN_WIDTH, SCREEN_HEIGHT - kTopBarHeight - originY)];
    view.tag = 12345;
    view.backgroundColor = QCWhite;
    [self.view addSubview:view];
    
    UIImageView *imageLogo = [[UIImageView alloc]init];
    imageLogo.image = fImageNamed(imageName);
    [view addSubview:imageLogo];
    [imageLogo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view.mas_centerX);
        make.centerY.equalTo(view.mas_centerY).offset(-90);
    }];
    
    UILabel *tipLbl = [[UILabel alloc] initWithFrame:CGRectZero];
    tipLbl.text = tipString;
    tipLbl.font = FONT_PR(16);
    [tipLbl sizeToFit];
    tipLbl.textColor = QCBlack;
    [view addSubview:tipLbl];
    [tipLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view.mas_centerX);
        make.centerY.equalTo(view.mas_centerY);
    }];
}

- (void)hideNoDataView {
    UIView *view = [self.view viewWithTag:12345];
    [view removeFromSuperview];
}

@end
